package com.o2o.app.userCenter;

/**
 * 发布二手信息
 */
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.o2o.app.BQApplication;
import com.o2o.app.MainActivity;
import com.o2o.app.R;
import com.o2o.app.adapter.MyPagerAdapter;
import com.o2o.app.utils.AlertTools;
import com.o2o.app.utils.DataUtil;
import com.o2o.app.utils.FileUtil;
import com.o2o.app.utils.MagusTools;
import com.o2o.app.utils.PhoneUtil;
import com.o2o.app.utils.SendCacheManager;

public class MinePublishInfoActivity extends Activity {
	public static final int GALLERY_ACTIVITY = 1002;
	public static final int CAMERA_ACTIVITY = 1001;

	private Button btn_publish;

	/**
	 * 返回按钮
	 */
	private Button btn_back;

	/**
	 * 拍照布局
	 */
	private LinearLayout llt_01;

	/**
	 * 拍照按钮
	 */
	private ImageView user_icon;

	/**
	 * 取消按钮
	 */
	private LinearLayout lly_cancel;

	/**
	 * 拍照那妞
	 */
	private LinearLayout lly_pic;

	/**
	 * 从手机相册选择
	 */
	private LinearLayout lly_img;

	/**
	 * Bitmap工厂中的Options对象，用于重绘Bitmap对象
	 */
	private BitmapFactory.Options opts = new BitmapFactory.Options();
	// bitmap资源
	private Bitmap bitmap = null;

	// 图片的二进制资源
	private byte[] picRes = null;

	// 文件大小
	private int picSize = 0;

	// 图片文件
	private String picPath = null;

	private Bitmap newbitmap = null;

	private ImageView label_add1, label_add2, label_add3, label_add4,
			label_add5, label_add6, label_add7, label_add8, label_add9,
			label_add10;

	private ImageView iv_add1;

	// 判断放第几个图片
	private int index_pic = 1;

	// 每张图片，是否可用
	private HashMap<Integer, Integer> list_count = new HashMap<Integer, Integer>();

	// 图片控件列表
	private ArrayList<ImageView> imgLists = new ArrayList<ImageView>();

	// 图片列表
	private ArrayList<Drawable> bitmapLists = new ArrayList<Drawable>();

	/**
	 * 头像详情
	 */
	private PopupWindow foodPop = null;

	private ArrayList<View> imageList = new ArrayList<View>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mine_publish_info);

		initViews();
	}

	private void initViews() {
		btn_publish = (Button) findViewById(R.id.btn_publish);
		btn_publish.setOnClickListener(new ClickEvent());

		// 返回按钮
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(new ClickEvent());

		llt_01 = (LinearLayout) findViewById(R.id.llt_01);

		user_icon = (ImageView) findViewById(R.id.user_icon);
		user_icon.setOnClickListener(new ClickEvent());

		// 取消按钮
		lly_cancel = (LinearLayout) findViewById(R.id.lly_cancel);
		lly_cancel.setOnClickListener(new ClickEvent());

		// 拍照
		lly_pic = (LinearLayout) findViewById(R.id.lly_pic);
		lly_pic.setOnClickListener(new ClickEvent());

		// 已选照片
		lly_img = (LinearLayout) findViewById(R.id.lly_img);
		lly_img.setOnClickListener(new ClickEvent());

		label_add1 = (ImageView) findViewById(R.id.label_add1);
		label_add1.setOnClickListener(new ClickEvent());
		imgLists.add(label_add1);

		label_add2 = (ImageView) findViewById(R.id.label_add2);
		label_add2.setOnClickListener(new ClickEvent());
		imgLists.add(label_add2);

		label_add3 = (ImageView) findViewById(R.id.label_add3);
		label_add3.setOnClickListener(new ClickEvent());
		imgLists.add(label_add3);

		label_add4 = (ImageView) findViewById(R.id.label_add4);
		label_add4.setOnClickListener(new ClickEvent());
		imgLists.add(label_add4);

		label_add5 = (ImageView) findViewById(R.id.label_add5);
		label_add5.setOnClickListener(new ClickEvent());
		imgLists.add(label_add5);

		label_add6 = (ImageView) findViewById(R.id.label_add6);
		label_add6.setOnClickListener(new ClickEvent());
		imgLists.add(label_add6);

		label_add7 = (ImageView) findViewById(R.id.label_add7);
		label_add7.setOnClickListener(new ClickEvent());
		imgLists.add(label_add7);

		label_add8 = (ImageView) findViewById(R.id.label_add8);
		label_add8.setOnClickListener(new ClickEvent());
		imgLists.add(label_add8);

		label_add9 = (ImageView) findViewById(R.id.label_add9);
		label_add9.setOnClickListener(new ClickEvent());
		imgLists.add(label_add9);

		label_add10 = (ImageView) findViewById(R.id.label_add10);
		label_add10.setOnClickListener(new ClickEvent());
		imgLists.add(label_add10);

		iv_add1 = (ImageView) findViewById(R.id.iv_add1);
		iv_add1.setOnClickListener(new ClickEvent());

		// 默认都可以点
		for (int i = 1; i < 11; i++) {
			list_count.put(i, 0);
		}
	}

	/**
	 * 点击事件
	 * 
	 * @author Administrator
	 * 
	 */
	class ClickEvent implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_publish: { // 发布
				Intent intent = new Intent(MinePublishInfoActivity.this,
						MinePublishDesActivity.class);

				startActivity(intent);
			}
				break;
			case R.id.btn_back: { // 返回
				finish();
			}
				break;

			case R.id.user_icon: { // 拍照
				llt_01.setVisibility(View.VISIBLE);
			}
				break;

			case R.id.lly_cancel: { // 拍照取消
				llt_01.setVisibility(View.GONE);
			}
				break;

			case R.id.lly_pic: { // 拍照
				tockenPicFromCamera();
			}
				break;

			case R.id.lly_img: { // 自取
				getPicFromLocal();
			}
				break;

			case R.id.iv_add1: {
				AlertTools.showTwoBtnAlert(MinePublishInfoActivity.this, "提示",
						"是否删除该图片", "是", "否",
						new DialogInterface.OnClickListener() {

							@SuppressLint("NewApi")
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								label_add1
										.setBackgroundResource(R.drawable.bj_tp);
								iv_add1.setVisibility(View.GONE);
							}
						}, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								arg0.dismiss();
							}
						});
			}
				break;

			case R.id.label_add1: {
//				if (bitmapLists.size() > 0 && bitmapLists.get(0) != null) {
//					foodPop = showPop(foodPop, bitmapLists.get(0));
//				}
//				BQApplication myApp = (BQApplication) getApplication();
//				myApp.setImageList(imageList);
//				
//				Intent intent = new Intent(MinePublishInfoActivity.this,
//						MainActivity.class);
//
//				startActivity(intent);
				
			}
				break;
			default:
				break;
			}
		}

	}

	
	private ViewPager vp_order_seat;
	private RadioGroup osIndicators;
	/**
	 * 头像详情
	 * 
	 * @param pop
	 * @return
	 */
	private PopupWindow showPop(PopupWindow pop, Drawable drawable) {
		if (pop == null) {
			pop = MagusTools.getPopupWindow(MinePublishInfoActivity.this,
					R.layout.demo1, R.style.wheel_animation,
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		}

		View view = pop.getContentView();

		vp_order_seat = (ViewPager) view.findViewById(R.id.vp_order_seat);
		osIndicators = (RadioGroup) view.findViewById(R.id.rg_order_seat_indicators);

		initGuideViewPager(imageList, osIndicators, vp_order_seat);
		
		View mainView = LayoutInflater.from(MinePublishInfoActivity.this)
				.inflate(R.layout.mine_publish_info, null);
		pop.showAtLocation(mainView, Gravity.CENTER, 0, 0);

		return pop;

	}
	
	/*
	 * 初始化广告展示条
	 */
	private void initGuideViewPager(List<View> picViews, final RadioGroup rg,
			ViewPager viewpager) {
		initIndicators(picViews, rg);

		MyPagerAdapter mPagerAdapter = new MyPagerAdapter(picViews);

		viewpager.setAdapter(mPagerAdapter);
		viewpager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
//				picindex = position;
				RadioButton radioButton = (RadioButton) rg.getChildAt(position);
				radioButton.setChecked(true);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}

	/**
	 * 初始化小点点
	 */
	private void initIndicators(List<View> picViews, RadioGroup rg) {
		for (int i = 0; i < picViews.size(); i++) {
			LayoutInflater layoutInflater = getLayoutInflater();
			RadioButton rbIndicator = (RadioButton) layoutInflater.inflate(
					R.layout.page_indicator, rg, false);
			rg.addView(rbIndicator);
		}
		if (picViews.size() > 0) {
			RadioButton radioButton = (RadioButton) rg.getChildAt(0);
			radioButton.setChecked(true);
		}
	}

	/**
	 * 拍照选择图片
	 */
	private void tockenPicFromCamera() {
		try {
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
					.fromFile(new File(Environment
							.getExternalStorageDirectory(), "/temp.jpg")));
			startActivityForResult(cameraIntent, CAMERA_ACTIVITY);
		} catch (ActivityNotFoundException e) {
			Log.i("[SendMBlogActivity------>tockenPicFromCamera()]:",
					"Activity Not Found Exception", e);
		}
	}

	/**
	 * 从本地获取图片
	 * 
	 * @return
	 */
	private void getPicFromLocal() {
		Intent localIntent = new Intent();
		localIntent.setType("image/*");
		localIntent.addCategory(Intent.CATEGORY_OPENABLE);
		localIntent.setAction("android.intent.action.GET_CONTENT");
		Intent localIntent2 = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(localIntent2, GALLERY_ACTIVITY);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		llt_01.setVisibility(View.GONE);
		if (RESULT_OK != resultCode && data == null) {
			return;
		} else {
			switch (requestCode) {
			case CAMERA_ACTIVITY: {
				opts.inSampleSize = 3;
				if (bitmap != null) {
					bitmap.recycle();
				}
				bitmap = BitmapFactory
						.decodeFile(Environment.getExternalStorageDirectory()
								+ "/temp.jpg", opts);

				SendCacheManager.setBitmapCache(bitmap);
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bitmap.compress(CompressFormat.JPEG, 80, stream);
				picRes = stream.toByteArray();
				picSize = stream.size();

				DataUtil.setPicRes(picRes);
				DataUtil.setPicSize(picSize);
				DataUtil.setPicPath(Environment.getExternalStorageDirectory()
						+ "/temp.jpg");

				// 自动旋转
				int degree = PhoneUtil.readPictureDegree(DataUtil.getPicPath());
				newbitmap = PhoneUtil.rotaingImageView(degree, bitmap);

				Drawable drawable = new BitmapDrawable(newbitmap);
				bitmapLists.add(drawable);
				showpic(drawable);

			}
				break;
			case GALLERY_ACTIVITY: {
				// 清理图片资源
				clearImage();

				Uri selectedImageUri = null;
				try {
					selectedImageUri = data.getData();

					// 获取图库图片
					getPicFromUri(selectedImageUri);

					if (selectedImageUri != null) {
						try {
							opts.inSampleSize = 3;
							if (bitmap != null) {
								bitmap.recycle();
							}
							bitmap = BitmapFactory.decodeStream(
									getContentResolver().openInputStream(
											selectedImageUri), null, opts);

						} catch (Exception e) {

						}
					}

					SendCacheManager.setBitmapCache(bitmap);
					int degree = PhoneUtil.readPictureDegree(DataUtil
							.getPicPath());
					newbitmap = PhoneUtil.rotaingImageView(degree, bitmap);
					// iv_pic.setImageBitmap(bitmap);
					Drawable drawable = new BitmapDrawable(newbitmap);
					bitmapLists.add(drawable);
					showpic(drawable);
				} catch (Exception e) {
				}
			}
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 判断显示第几张图片
	 */
	private void showpic(Drawable drawable) {
		// 大于0 ，说明已有图片
		if (list_count.get(index_pic) > 0) {
			return;
		}
		switch (index_pic) {
		case 1: {
			label_add1.setBackgroundDrawable(drawable);
			// iv_add1.setVisibility(View.VISIBLE);
			imageList.add(label_add1);
			
			list_count.put(1, 1);
		}
			break;
		case 2: {
			label_add2.setBackgroundDrawable(drawable);
			imageList.add(label_add2);
			list_count.put(2, 1);
		}
			break;
		case 3: {
			label_add3.setBackgroundDrawable(drawable);
			list_count.put(3, 1);
		}
			break;
		case 4: {
			label_add4.setBackgroundDrawable(drawable);
			list_count.put(4, 1);
		}
			break;
		case 5: {
			label_add5.setBackgroundDrawable(drawable);
			list_count.put(5, 1);
		}
			break;
		case 6: {
			label_add6.setBackgroundDrawable(drawable);
			list_count.put(6, 1);
		}
			break;
		case 7: {
			label_add7.setBackgroundDrawable(drawable);
			list_count.put(7, 1);
		}
			break;
		case 8: {
			label_add8.setBackgroundDrawable(drawable);
			list_count.put(8, 1);
		}
			break;
		case 9: {
			label_add9.setBackgroundDrawable(drawable);
			list_count.put(9, 1);
		}
			break;
		case 10: {
			label_add10.setBackgroundDrawable(drawable);
			list_count.put(10, 1);
		}
			break;

		default:
			break;
		}

		index_pic++;
	}

	/**
	 * 获取图片名
	 * 
	 * @param uri
	 *            图片的URI
	 */
	private void getPicFromUri(Uri uri) {
		try {
			String[] data = { MediaStore.Images.Media.DATA };
			@SuppressWarnings("deprecation")
			Cursor cursor = managedQuery(uri, data, null, null, null);
			if (cursor != null) {
				int index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				picPath = cursor.getString(index);
			} else {
				picPath = Uri.decode(uri.toString());
				picPath = picPath.replace("file://", "");
			}
			File file = new File(picPath);
			picSize = (int) file.length();
			picRes = FileUtil.getFileBytes(picPath);

			DataUtil.setPicPath(picPath);
			DataUtil.setPicRes(picRes);
			DataUtil.setPicSize(picSize);
		} catch (Exception e) {
		}

	}

	/**
	 * 清理图片资源
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void clearImage() {
		DataUtil.setPicRes(null);
		DataUtil.setPicSize(0);
		DataUtil.setPicPath("");
	}

}
